<template>
    <div class='container'>
        <div class="edit">
            <MdEditor v-model="text" @on-save="handleSave" />
        </div>
        <div class="readonly">
            <MdPreview :editorId="id" :modelValue="preview_text" />
            <MdCatalog :editorId="id" :scrollElement="scrollElement" />
        </div>
    </div>
    <br></br>
    {{ text }}
    <br></br>
    {{ escapeString(text) }}
    <!-- <MdPreview :modelValue="addHeadingNumbers(escapeString(text))" /> -->
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { MdPreview, MdCatalog, MdEditor } from 'md-editor-v3';
import { getMdAPI } from '@/api/md'
import 'md-editor-v3/lib/preview.css';
import 'md-editor-v3/lib/style.css';
const preview_text = ref()

const content = ref()
const handleSave = (text: string) => {
    console.log(text);
    content.value = escapeString(text)
}

const id = 'preview-only';
const text = ref(`# This is a god student
> Hello \n\`\`\`
import pandas as pd\n\`\`\`\n
$$
\\frac{a^2}{2x^2+bx+c}
$$
`);

const scrollElement = document.documentElement;


function escapeString(str: string): string {
    return str
        // .replace(/[\\"]/g, '\\$&')  // 转义 \ 和 "
        .replace(/\n/g, '\\n')
        .replace(/\t/g, '\\t')
        .replace(/\r/g, '\\r')
        .replace(/\f/g, '\\f')
        .replace(/\`/g, '\\`')
}

function addHeadingNumbers(markdown: string): string {
    const lines = markdown.split('\n');
    const headingLevels: number[] = [0, 0, 0, 0, 0, 0]; // 最多支持6级标题

    return lines
        .map((line) => {
            const headingMatch = line.match(/^#+/);
            if (!headingMatch) return line;

            const level = headingMatch[0].length - 1; // 一级标题 level = 0
            const rest = line.slice(level + 1).trim();

            // 清除比当前 level 深的层级
            for (let i = level + 1; i < headingLevels.length; i++) {
                headingLevels[i] = 0;
            }

            // 当前层级编号 +1
            headingLevels[level] += 1;

            // 构造序号，从第一个非零值开始
            const path = headingLevels.slice(0, level + 1);
            const startIndex = path.findIndex((n) => n > 0);
            const numberPrefix = path
                .slice(startIndex, level + 1)
                .join('.')
                .replace(/^0/, '1'); // 防止从 0 开始（比如第一个标题是三级）

            return `${'#'.repeat(level + 1)} ${numberPrefix}. ${rest}`;
        })
        .join('\n');
}
onMounted(async () => {
    const res = await getMdAPI()
    console.log("getMdAPI-获取Markdown", res)
    preview_text.value = addHeadingNumbers(res)
})
</script>
<style lang='scss' scoped>
.container {
    display: inline-flex;
    justify-content: space-between;
    gap: 30px;

    .edit {
        width: 1200px;
        height: 100%;
    }

    .readonly {
        width: 600px;
        height: 100%;
    }
}
</style>
